package main

import (
	"context"
	"fmt"

	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/metadata"
	"google.golang.org/grpc/status"
	"log"
	"net"
	"strings"
	"gin-gateway/example/gateway_demo/otherProxy/grpc_proxy"
	"google.golang.org/grpc/credentials/insecure"
	"google.golang.org/grpc/encoding"
)

const (
	port = ":50051" // 本服务ip:port
)

func main() {
	Listen, err := net.Listen("tcp", port)
	if err != nil {
		log.Fatalf("failed to listen: %v", err)
	}
	encoding.RegisterCodec(grpc_proxy.Codec()) // 设置grpcServer 全局使用编解码
	director := func(ctx context.Context, fullMethodName string) (context.Context, *grpc.ClientConn, error) {
		if strings.HasPrefix(fullMethodName, "/com.example.internal.") { // 匹配方法 // 拒绝某些特殊请求方法
			return ctx, nil, status.Errorf(codes.Unimplemented, "Unknown method")
		}

		//ClientConn, err := grpc.DialContext(ctx, "localhost:50055", grpc.WithCodec(grpc_proxy.Codec()), grpc.WithInsecure())
		ClientConn, err := grpc.NewClient("localhost:50055", // 下游服务
			grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithDefaultCallOptions(grpc.ForceCodec(grpc_proxy.Codec())))
		md, _ := metadata.FromIncomingContext(ctx)
		outCtx, _ := context.WithCancel(ctx)
		outCtx = metadata.NewOutgoingContext(outCtx, md.Copy())
		return outCtx, ClientConn, err
	}

	grpcServer := grpc.NewServer(grpc.UnknownServiceHandler(grpc_proxy.TransparentHandler(director)))
	fmt.Printf("server listening at %v\n", Listen.Addr())
	if err := grpcServer.Serve(Listen); err != nil {
		log.Fatalf("failed to serve: %v", err)
	}
}
